package com.ic.loan.activity

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import com.appsflyer.AppsFlyerLib
import com.blankj.utilcode.util.*
import com.gyf.immersionbar.ktx.immersionBar
import com.ic.loan.R
import com.ic.loan.bean.LoginBean
import com.ic.loan.bean.MyInfo
import com.ic.loan.bean.MyWallet
import com.ic.loan.cache.Constant
import com.ic.loan.http.ApiUrl
import com.ic.loan.http.HttpUtils
import com.ic.loan.http.ResultListener
import com.ic.loan.pop.PrivacyPolicyPop
import com.lxj.xpopup.XPopup
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach

class LoginActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        immersionBar {
            statusBarDarkFont(true)
        }
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        initView()
        tvLogin.setOnClickListener {
            login()
        }
        tvGetCode.setOnClickListener {
            getCode()
        }
    }

    private fun getCode() {
        showLoading()
        val mobile = edtMobile.text.toString()
        val map = mutableMapOf<String, Any>()
        map["mobile"] = "91${mobile}"
        HttpUtils.postOkGo(map, ApiUrl.POST_SMS_CODE, object : ResultListener() {
            override fun onSucceeded(json: String?) {
                countDownCoroutines(60,{
                    tvGetCode.text = "${it}S"
                    tvGetCode.isEnabled = false
                },{
                    tvGetCode.isEnabled = true
                    tvGetCode.text = getString(R.string.enter_otp)
                })
            }

            override fun onLoadFinish() {
                super.onLoadFinish()
                hintLoading()
            }
        },true)
    }

    private fun initView() {
        SpanUtils.with(tvIAgree)
            .append("I agree  to")
            .setFontSize(36)
            .appendSpace(ConvertUtils.dp2px(10f))
            .append("PRIVACY POLICY.")
            .setBackgroundColor(ColorUtils.getColor(android.R.color.transparent))
            .setForegroundColor(ColorUtils.getColor(android.R.color.transparent))
            .setClickSpan(Color.parseColor("#F37E20"), true) {
                XPopup.Builder(this).asCustom(PrivacyPolicyPop(this)).show()
            }
            .setFontSize(48)
            .appendLine()
            .append("TERMS AND CONDITIONS,")
            .setFontSize(48)
            .setClickSpan(Color.parseColor("#F37E20"), true) {
                ActivityUtils.startActivity(TermsOfConditionsActivity::class.java)
            }
            .create()
        SPUtils.getInstance().remove(Constant.TOKEN)
        SPUtils.getInstance().remove(Constant.APPLY_SUCCESS)
        ActivityUtils.finishOtherActivities(LoginActivity::class.java)
    }

    private fun login() {
        val mobile = edtMobile.text.toString()
        val msgCode = edtCode.text.toString()
        if (mobile.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_input_mobile_number))
            return
        }
        if (msgCode.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_input_opt))
            return
        }
        val map = mutableMapOf<String, Any>()
        map["mobile"] = "91${mobile}"
        map["code"] = msgCode
        showLoading()
        HttpUtils.postOkGo(map, ApiUrl.POST_LOGIN, object : ResultListener() {
            override fun onSucceeded(json: String?) {
                val loginBean = GsonUtils.fromJson(json,LoginBean::class.java)
                if (loginBean.token.isNotEmpty()){
                    SPUtils.getInstance().put(Constant.TOKEN,loginBean.token)
//                    ActivityUtils.startActivity(StartActivity::class.java)
//                    onBackPressed()
                    getStatus()
                }
            }

            override fun onFailed(content: String?) {
                super.onFailed(content)
                hintLoading()
            }

            override fun onErr(e: String?) {
                super.onErr(e)
                hintLoading()
            }
        })
    }

    fun countDownCoroutines(total:Int,onTick:(Int)->Unit,onFinish:()->Unit,
                            scope: CoroutineScope = GlobalScope
    ): Job {
        return flow{
            for (i in total downTo 0){
                emit(i)
                delay(1000)
            }
        }.flowOn(Dispatchers.Default)
            .onCompletion { onFinish.invoke() }
            .onEach { onTick.invoke(it) }
            .flowOn(Dispatchers.Main)
            .launchIn(scope)
    }

    private fun getStatus() {
        HttpUtils.postOkGo(
            mutableMapOf("timestamp" to System.currentTimeMillis() / 1000),
            ApiUrl.POST_USER_PROFILE,
            object : ResultListener() {
                override fun onSucceeded(json: String?) {
                    val myInfo = GsonUtils.fromJson(json, MyInfo::class.java)
                    when {
                        myInfo.balance.toDouble() > 0.0 -> {
                            ActivityUtils.startActivity(MainActivity::class.java)
                            hintLoading()
                            onBackPressed()
                        }
                        myInfo?.fullname.isNullOrBlank() -> {
                            if (SPUtils.getInstance().getInt(Constant.APPLY_SUCCESS) == 1){
                                ActivityUtils.startActivity(MyInformationActivity::class.java)
                            }else{
                                ActivityUtils.startActivity(StartActivity::class.java)
                            }
                            hintLoading()
                            onBackPressed()
                        }
                        else -> {
                            //获取钱包数据
                            updateApproval()
                        }
                    }
                }

                override fun onErr(e: String?) {
                    super.onErr(e)
                    hintLoading()
                }

                override fun onFailed(content: String?) {
                    super.onFailed(content)
                    hintLoading()
                }

            })
    }

    private fun updateApproval() {
        HttpUtils.postOkGo(mutableMapOf("timestamp" to System.currentTimeMillis() / 1000),
            ApiUrl.POST_USER_MYWALLET,object : ResultListener() {
                override fun onSucceeded(json: String?) {
                    val myWallet = GsonUtils.fromJson(json, MyWallet::class.java)
                    if (myWallet.app_amount.toDouble() > 0){
                        ActivityUtils.startActivity(MainActivity::class.java)
                        onBackPressed()
                    }else{
                        ActivityUtils.startActivity(WhyChooseUsActivity::class.java)
                        onBackPressed()
                    }
                }

                override fun onLoadFinish() {
                    super.onLoadFinish()
                    hintLoading()
                }
            })
    }



}